/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yy.bugzillahelp.ui.server;

import com.yy.bugzillahelp.data.server.ServerData;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author hualun-alan
 */
public class ServerTree extends JTree {

    private ServerPopupMenu popupMenu;
    private DefaultMutableTreeNode rootNode;
    private DefaultTreeModel model;

    public ServerTree() {
        rootNode = new DefaultMutableTreeNode("Connections");
        model = new DefaultTreeModel(rootNode);
        this.setModel(model);

        popupMenu = new ServerPopupMenu(this);


        this.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                int button = e.getButton();
                if (button == MouseEvent.BUTTON3) {
                    System.out.println("3");
                    rightMouseAction(e);
                }
            }
        });
    }

    private void rightMouseAction(MouseEvent e) {
        TreePath pathForLocation = this.getPathForLocation(e.getX(), e.getY());
        this.setSelectionPath(pathForLocation);
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) this.getLastSelectedPathComponent();
        System.out.println(node);
        if (node.isLeaf() && node.getParent() != null) {
            ServerNode connectNode = (ServerNode) node;
            popupMenu.setConnectData(connectNode.getConnectData());
            popupMenu.show(this, e.getX(), e.getY());
        }
    }

    public void addNode(ServerData connectData) {
        rootNode.add(new ServerNode(connectData));
        model.nodeStructureChanged(rootNode);
    }

    public void removeNode(ServerData connectData) {
        int childCount = rootNode.getChildCount();
        for (int i = 0; i < childCount; i++) {
            ServerNode node = (ServerNode) rootNode.getChildAt(i);
            if (node.getConnectData().toString().equals(connectData.toString())) {
                rootNode.remove(node);
                break;
            }
        }

        model.nodeStructureChanged(rootNode);

    }
}
